package list;


public class DirtyArrayList extends AbstractList {
	public static final int STEP = 1;
	private Object[] data;;

	public DirtyArrayList() {
	}

	public DirtyArrayList(Object[] objects) {
		super(objects);
	}

	@Override
	public void add(int index, Object object) {
		if (index > size) {
			throw new IndexOutOfBoundsException();
		}
		if (data == null) {
			data = new Object[1];
			size = 1;
			data[0] = object;
			return;
		}
		Object[] tmp = new Object[data.length + 1];
		for (int i = 0; i < data.length; i++) {
			tmp[i] = data[i];
		}
		for (int i = tmp.length - 1; i > index; i--) {
			tmp[i] = tmp[i - 1];
		}
		tmp[index] = object;
		data = tmp;
		size++;
	}

	@Override
	public void clear() {
		data = null;
	}

	@Override
	public boolean contains(Object object) {
		boolean result = false;
		for (Object o : data) {
			if (o != null && o.equals(object)) {
				result = true;
				break;
			}
		}
		return result;
	}

	@Override
	public Object get(int index) {
		return data[index];
	}

	@Override
	public int lastIndexOf(Object object) {
		int index = -1;
		for (int i = data.length - 1; i >= 0; i--) {
			if (data[i].equals(object)) {
				index = i;
				break;
			}
		}
		return index;
	}

	@Override
	public void remove(int index) {
		if (index > size - 1) {
			throw new IndexOutOfBoundsException();
		}
		int oriLength = data.length;
		Object[] newArray = new Object[oriLength];
		for (int i = index; i < oriLength - 1; i++) {
			data[i] = data[i + 1];
		}
		newArray = data;
		data = new Object[oriLength - 1];
		for (int i = 0; i < oriLength - 1; i++) {
			data[i] = newArray[i];
		}
		size--;
	}

	@Override
	public void set(int index, Object object) {
		data[index] = object;
	}

	public String toString() {
		if (data == null) {
			return null;
		}
		StringBuilder sb = new StringBuilder("[");
		for (Object o : data) {
			sb.append(o).append(",");
		}
		sb.replace(sb.length() - 1, sb.length(), "]");
		sb.append(size);
		return sb.toString();
	}
}
